package com.haolp.sys.service.impl;

import com.haolp.sys.common.exception.ServiceException;
import com.haolp.sys.common.vo.PageObjectVO;
import com.haolp.sys.common.vo.SysUserDeptVo;
import com.haolp.sys.dao.SysUserDao;
import com.haolp.sys.dao.SysUserRoleDao;
import com.haolp.sys.pojo.SysUser;
import com.haolp.sys.service.SysUserService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 小李
 * @version 1.0
 * @date 2021/10/12 15:40
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public PageObjectVO<SysUserDeptVo>
    findPageObjects(String username, Integer pageCurrent) {
        //1.参数效验
        if (pageCurrent == null || pageCurrent < 1)
            throw new IllegalArgumentException("当前页码值无效");
        //2.查询总记录数
        int rowCount = sysUserDao.getRowCount(username);
        if (rowCount == 0)
            throw new ServiceException("记录不存在");
        //3.计算startIndex的值
        int pageSize = 3;
        int startIndex = (pageCurrent - 1) * pageSize;
        List<SysUserDeptVo> records =
                sysUserDao.findPageObjects(username, startIndex, pageSize);
        //4.返回数据
        PageObjectVO<SysUserDeptVo> po=new PageObjectVO<>
                (pageCurrent,pageSize,rowCount,records);
        return po;
    }


    @Override
    public int updatePassword(String pwd, String newPwd, String cfgPwd) {
        //1.参数非空效验
        if (StringUtils.isEmpty(pwd))
            throw new IllegalArgumentException("原密码不能为空");
        if (StringUtils.isEmpty(newPwd))
            throw new IllegalArgumentException("新密码不能为空");
        //2.等值校验
        if (!newPwd.equals(cfgPwd))
            throw new IllegalArgumentException("新密码与确认密码不一致");
        //3.效验原密码是否正确
       //获取当前登录的用户信息
        SysUser sysUser=(SysUser) SecurityUtils.getSubject().getPrincipal();
        String hashPassword=sysUser.getPassword();
        String salt=sysUser.getSalt();
        SimpleHash sh=new SimpleHash("MD5",pwd,salt,1);
        if (!hashPassword.equals(sh.toHex()))
            throw new IllegalArgumentException("原密码不正确");
        //4.修改密码
        salt=UUID.randomUUID().toString();
        sh=new SimpleHash("MD5", newPwd,salt,1);
        String haseNewPwd=sh.toHex();
        int rows=sysUserDao.updatePassword(haseNewPwd, salt, sysUser.getId());
        //5.返回结果
        return 0;
    }

    @Override
    public int updateObject(SysUser entity, Integer[] roleIds) {
        //1.参数效验
        if (entity==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if (StringUtils.isEmpty(entity.getUsername()))
            throw new IllegalArgumentException("用户名不能为空");
        if (roleIds==null || roleIds.length==0)
            throw new ServiceException("必须为用户赋予角色");
        //2.更新用户信息
        int rows = sysUserDao.updateObject(entity);
        //3.保存用户与角色信息
        //3.1 基于用户Id删除原有关系数据
        sysUserRoleDao.deleteObjectsByUserId(entity.getId());
        //3.2 基于用户id和角色ids新增关系数据
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        //4.效验并返回结果
        return rows;
    }

    @Override
    public Map<String, Object> findObjectById(Integer userId) {
        //1.参数效验
        if(userId==null || userId<1)
            throw new IllegalArgumentException("id值无效");
        //2.基于id查询
        SysUserDeptVo sysUserDeptVo = sysUserDao.findObjectById(userId);
        if (sysUserDeptVo==null)
            throw new ServiceException("该记录可能不存在");
        List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(userId);
        //3.封装结果并返回
        Map<String,Object> map=new HashMap<>();
        map.put("user", sysUserDeptVo);
        map.put("roleIds", roleIds);
        return map;
    }

    @Override
    public int saveObject(SysUser entity, Integer[] roleIds) {
        //1.参数效验
        if (entity==null)
            throw new IllegalArgumentException("保存对象不能为空");
        if (StringUtils.isEmpty(entity.getUsername()))
            throw new IllegalArgumentException("用户名不能为空");
        if(StringUtils.isEmpty(entity.getPassword()))
            throw new IllegalArgumentException("密码不能为空");
        if (roleIds==null || roleIds.length==0)
            throw new ServiceException("必须为用户赋予角色");
        //2.保存用户信息
        //2.1对密码进行加密(md5盐值加密)
        String salt = UUID.randomUUID().toString();
        SimpleHash sh=new SimpleHash(
                "MD5",
                entity.getPassword(),
                salt,
                1);
        //将加密结果转换为16进制
        String newPassword=sh.toHex();
        entity.setSalt(salt);
        entity.setPassword(newPassword);
        //2.2保存用户自身信息
        int rows = sysUserDao.insertObject(entity);
        //2.3保存用户与角色的关系数据
        sysUserRoleDao.insertObjects(entity.getId(), roleIds);
        //3.返回结果
        return rows;
    }
    @RequiresPermissions("sys:user:update")
    @Override
    public int validById(Integer id, Integer valid, String modifiedUser) {
        //1.合法性效验
        if(id==null || id<=0)
            throw new IllegalArgumentException("参数不合法，id="+id);
        if(valid !=1 && valid !=0)
            throw new ServiceException("参数不合法，valid="+valid);
        if(StringUtils.isEmpty(modifiedUser))
            throw new ServiceException("修改用户不能为空");
        //2.执行禁用或启用操作
        int rows=0;
        try{
             rows = sysUserDao.validById(id, valid, "admin");
        }catch (Throwable e){
            e.printStackTrace();
            throw new ServiceException("系统正在维护，请稍后重试...");
        }

        //3.对结果进行验证，并返回
        return rows;
    }
}
